import {getUserInfo,userLogin,userLogout} from "@/api/user"

const state = {
  token:localStorage.getItem("key_token") || "" ,
  userInfo:{}
}

const mutations = {
  //拿到用户信息
  GET_USERINFO(state,userInfo){
    state.userInfo = userInfo
  },
  //拿到用户token
  GET_TOKEN(state,token){
    state.token = token
  },
  //退出清空token
  CLEAT_TOKEN(state,token){
    state.token = ""
  },
  //退出清空用户信息
  RESET_USERINFO(state){
    state.userInfo = {}
  }
} 

const actions = {
  //用户登录成功获取用户信息
  async login({commit},userInfo) {
    try{
       const result = await userLogin(userInfo)
       if(result.code === 20000){
         // console.log(result);
         commit("GET_TOKEN",result.data.token)
         localStorage.setItem('key_token',result.data.token)
         return "yes"
       }else{
         return Promise.reject(new Error('failed'))
       }
    }catch(error){
       return Promise.reject(new Error('failed'))
    }
 },

  //用户登录成功获取用户token
  async getInfo ({commit}) {
    try{
       const result = await getUserInfo()
       console.log("222")
      //  console.log(result)
       if(result.code === 20000){
        commit("GET_USERINFO",result.data)
          return "yes"
          // console.log("333")
       }else{
      return Promise.reject(new Error('failed'))
       }
    }catch(error){
      return Promise.reject(new Error('failed'))
    }
  },
  
  //用户退出登录清空token和用户信息
  // async logout({commit},dispatch){
  //   try{
  //     const result = await userLogout()
  //     if(result.code === 20000){
  //       dispatch("resetToken")
  //       commit('RESET_USERINFO')
  //       return "yes"
  //     }else{
  //       return Promise.reject(new Error('failed'))
  //     }
  //   }catch(error){
  //     return Promise.reject(new Error('failed'))
  //   }
  // },
  
  //退出登录时候清空用户token
  // resetToken({commit}){
  //   commit("CLEAT_TOKEN")
  //   localStorage.removeItem("key_token")
  // }
 
} 

const getters = {}

export default {
  namespaced : true ,
  state ,
  mutations,
  actions,
  getters
}